const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
const router = new Router()
const bodyParser = require('koa-bodyparser');
const axios = require('axios') 
app.use(async(ctx, next) => {  // 处理跨域
  ctx.set('Access-Control-Allow-Origin', '*');  // 允许所有域名访问我这个后端
  ctx.set('Access-Control-Allow-Methods', 'OPTIONS, GET, PUT, POST, DELETE'); // 允许的请求方法
  ctx.set('Access-Control-Allow-Headers', 'x-requested-with, accept, origin, content-type'); // 允许的请求头
  // 请求预检（http协议规定每一个 http 请求发送前都会自动发送一个预检请求）
  if (ctx.method === 'OPTIONS') {
    ctx.status = 204
    return;
  }

  await next();
})


app.use(bodyParser())
router.post('/deepseek/chat', async (ctx) => {
    const message = ctx.request.body.content  // 前端传过来的消息
    const data = {
        model: 'deepseek-r1:1.5b',
        messages: [
            {
                role: 'user',
                content: message
            }
        ],
        stream: false
    } 
    await axios.post("http://localhost:11434/api/chat", data).then((res) => { 
        ctx.body = {
            code: 200,
            content: res.data.message.content
        } 
      
     }) 
    
})





app.use(router.routes())



app.listen(3000, () => {
    console.log('开启后端的端口');

})